#include "bintree.h"

BinTree::BinTree()
{
	left = right = NULL;
	value = NULL;
}

BinTree::BinTree(Token* in)
{
	left = right = NULL;
	value = in;
}

BinTree::~BinTree()
{
	if(left) delete left;
	if(right) delete right;
	if(value) delete value;
}

void BinTree::insert(Token* in, int lineNumber)
{
	if(value)
	{
		int dir = strcmp(value->getTokenString().c_str(), in->getTokenString().c_str());
		if(dir > 0)
		{
			if(right)
			{
				right->insert(in, lineNumber);
			}
			else
			{
				right = new BinTree(in);
				right->value->appendLineNumber(lineNumber);
			}
		}
		else if(dir < 0)
		{
			if(left)
			{
				left->insert(in, lineNumber);
			}
			else
			{
				left = new BinTree(in);
				left->value->appendLineNumber(lineNumber);
			}
		}
		else
		{
			value->appendLineNumber(lineNumber);
			delete in; // Since we're not using in anymore, we need to get rid of it
		}
	}
	else
	{
		value = in;
		value->appendLineNumber(lineNumber);
	}
}

void BinTree::print()
{
	// I love functional programming
	if(right) right->print();
	printf("%-16s", value->getTokenString().c_str());
	value->printLines();
	printf("\n");
	if(left) left->print();
}
